import os
from logging.handlers import TimedRotatingFileHandler

from dotenv import load_dotenv

load_dotenv()

import logging


class LoggerConfig:
    def __init__(
            self,
            app=None,
            log_dir="logs",
            max_bytes=16777216,  # 16MB
            backup_count=7,
            when="midnight",  # 每天轮转
            interval=1,
            console_level=logging.DEBUG,
            file_level=logging.NOTSET,
            log_format=None,
    ):
        self.app = app
        self.log_dir = log_dir
        self.max_bytes = max_bytes
        self.backup_count = backup_count
        self.when = when
        self.interval = interval
        self.console_level = console_level
        self.file_level = file_level

        # 默认日志格式
        self.log_format = log_format or (
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
        )

        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        """将日志配置应用到 Flask app"""
        self.app = app
        self.setup()

    def setup(self):
        """配置日志处理器"""
        if not self.app:
            raise RuntimeError("Flask app not initialized.")

        # 确保日志目录存在
        if not os.path.exists(self.log_dir):
            os.makedirs(self.log_dir)

        # 创建 formatter
        formatter = logging.Formatter(self.log_format)

        # 获取 app 的 logger
        logger = self.app.logger
        logger.setLevel(logging.DEBUG)  # 设置为最低级别，由 handler 控制输出

        # 防止重复添加处理器
        for handler in logger.handlers[:]:
            logger.removeHandler(handler)

        # 1. 文件处理器：按时间轮转（每天）
        file_handler = TimedRotatingFileHandler(
            filename=os.path.join(self.log_dir, "app.log"),
            when=self.when,
            interval=self.interval,
            backupCount=self.backup_count,
            encoding='utf-8'
        )
        file_handler.setLevel(self.file_level)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

        # 2. 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(self.console_level)
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)

        # 设置 propagate 为 False，防止重复输出
        logger.propagate = False

        # 记录启动日志
        logger.info("日志配置成功： %s", os.path.join(self.log_dir, "app.log"))

    def close_handlers(self):
        """关闭所有处理器（用于测试或重启时）"""
        for handler in self.app.logger.handlers[:]:
            handler.close()
            self.app.logger.removeHandler(handler)
